const { baseQuery } = require("./mongo_util");
const collectionName = "articles";

// 增博客  blogMdodel.addBlog(blog,onRetGot,onErrGot)
function addBlog(blog, onRetGot, onErrGot) {
    baseQuery(
        collectionName,
        (collection) => {
            return collection.insertOne(blog);
        },
        onRetGot,
        onErrGot
    );
}

// 删博客  blogMdodel.deleteBlog(bid,onRetGot,onErrGot)
function deleteBlog(bid, onRetGot, onErrGot) {
    baseQuery(
        collectionName,
        (collection) => {
            return collection.deleteOne({ id: bid });
        },
        onRetGot,
        onErrGot
    );
}

// 改博客  blogMdodel.updateBlog(blog,onRetGot,onErrGot)
function updateBlog(blog, onRetGot, onErrGot) {
    baseQuery(
        collectionName,
        (collection) => {
            const updateDoc = {
                $set: {
                    title: blog.title,
                    content: blog.content,
                },
            };
            return collection.updateOne({ id: blog.id }, updateDoc);
        },
        onRetGot,
        onErrGot
    );
}

// 查博客  blogMdodel.getBlogs(skip,limit,onRetGot,onErrGot)
function getBlogs(skip, limit, onRetGot, onErrGot) {
    baseQuery(
        collectionName,
        (collection) => {
            return collection.find().skip(skip).limit(limit).toArray();
        },
        onRetGot,
        onErrGot
    );
}

module.exports = {
    addBlog,
    deleteBlog,
    updateBlog,
    getBlogs,
};
